'use strict';
const Service = require('egg').Service;

class MongoCacheService extends Service {

	/**
	 * @param { String } key 键
	 * @param {String | Object | array} value 值
	 * @param { Number } expir 过期时间 单位秒
	 * @return { String } 返回成功字符串OK
	 */
	async set(key, value, expir = 0) {
    const { model } = this.ctx;
    const query = { key };
    const result = await model.MongoCache.findOne(query);
    
    let cache = new this.ctx.model.MongoCache();

    if (!result) {
      cache.key = key;
      cache.value = value;
      if (expir) {
        cache.expired_at = dayjs().add(expir, 'second').toDate();;
      }
      await cache.save();
    }

    const update = {
      value: value, 
    }

    if (expir) {
      update.expired_at = dayjs().add(expir, 'second').toDate();
    }

    await model.MongoCache.findOneAndUpdate(query, {
      ...update,
    });
	}

	/**
	 * 获取 redis 缓存
	 * @param { String } key 键
	 * @return { String | array | Object } 返回获取的数据
	 */
	async get(key) {
    const { model } = this.ctx
    const query = { key };
    const result = await model.MongoCache.findOne(query);
    
    if (!result) {
      return []
    }
		return [ result.value ]
  }
  
	/**
	 * 删除指定key
	 * @param {String} key 
	 */
	async remove(key) {
    const { model } = this.ctx
    const query = { key };
    await model.MongoCache.remove(query);
	}

	/**
	 * 清空缓存
	 */
	async clear() {
    const { model } = this.ctx
		await model.MongoCache.remove({ });
	}
}

module.exports = MongoCacheService;
